#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
登录处理器
使用DrissionPage库实现自动登录功能
"""

import logging
import os
import time
from typing import Dict, Any, Optional
from DrissionPage import ChromiumPage

logger = logging.getLogger(__name__)

class LoginHandler:
    """
    登录处理器，负责自动登录到教学评价系统
    """
    
    def __init__(self, config: Dict[str, Any] = None):
        """
        初始化登录处理器
        
        Args:
            config: 登录配置，包含URL、超时等信息
        """
        self.config = config or {}
        self.login_url = self.config.get('login_url', 'http://wspj.gxmu.edu.cn/login.jsp')
        self.success_url = 'http://wspj.gxmu.edu.cn/new/student/student_login/index.jsp'
        self.username = self.config.get('username', '20234092832')
        self.password = self.config.get('password', 'Gxmu@20234092832')
        self.timeout = self.config.get('timeout', 30)
        self.retry_count = self.config.get('retry_count', 3)
        self.page = None
    
    def initialize(self) -> bool:
        """
        初始化浏览器页面
        
        Returns:
            bool: 初始化是否成功
        """
        try:
            # 使用最简单的初始化方式
            self.page = ChromiumPage()
            
            return True
        except Exception as e:
            return False
    
    def login(self, username: str = None, password: str = None) -> bool:
        """
        登录到教学评价系统
        
        Args:
            username: 用户名，不提供则使用默认值
            password: 密码，不提供则使用默认值
            
        Returns:
            bool: 登录是否成功
        """
        if not self.page:
            if not self.initialize():
                return False
        
        username = username or self.username
        password = password or self.password
        
        try:
            # 导航到登录页面
            self.page.get(self.login_url)
            time.sleep(1.5)  # 等待1500毫秒
            
            # 定位用户名输入框 (通过ID查找)
            username_input = self.page.ele(locator='#TxtUserName')
            if not username_input:
                return False
            
            # 点击用户名输入框，清除默认值，然后输入用户名
            username_input.click()
            time.sleep(1.5)  # 等待1500毫秒
            username_input.clear()
            username_input.input(username)
            
            # 定位并点击密码输入框 (通过ID查找)
            password_visible = self.page.ele(locator='#TxtPassword')
            if not password_visible:
                return False
            
            # 点击密码框，使隐藏的密码输入框可见
            password_visible.click()
            time.sleep(1.5)  # 等待1500毫秒
            
            # 现在查找隐藏的密码输入框并输入
            password_input = self.page.ele(locator='#pwd')
            if not password_input:
                # 如果没有找到隐藏的密码框，尝试直接在可见框中输入
                password_visible.input(password)
            else:
                # 直接修改style属性使其显示
                self.page.run_js('document.getElementById("pwd").style.display="block";')
                time.sleep(1.5)  # 等待1500毫秒
                password_input.input(password)
            
            # 定位登录按钮 (通过ID查找)
            login_button = self.page.ele(locator='#IbtnEnter')
            if not login_button:
                return False
            
            # 点击登录按钮
            login_button.click()
            time.sleep(12)  # 增加等待时间到12秒
            
            # 直接返回True，不再检查URL
            logger.info("等待12秒后自动判定登录成功")
            return True
            
        except Exception as e:
            logger.error(f"登录过程中发生异常: {e}")
            return False
    
    def navigate_to_evaluation_page(self) -> bool:
        """
        导航到评教页面
        
        Returns:
            bool: 导航是否成功
        """
        if not self.page:
            logger.error("浏览器未初始化")
            return False
        
        try:
            
            # 检查当前URL，如果已经是评教页面则不需要重新导航
            current_url = self.page.url
            if "lzdx_evaluate.jsp" in current_url:
                return True

            # 添加JavaScript代码隐藏autocomplete警告
            hide_warnings_js = """
            // 隐藏所有可能的autocomplete警告
            var warnings = document.querySelectorAll('[class*="warning"], [class*="alert"], [class*="notice"], .chromium-warning');
            warnings.forEach(function(warning) {
                if(warning.textContent && warning.textContent.includes('autocomplete')) {
                    warning.style.display = 'none';
                }
            });
            
            // 添加CSS规则隐藏可能出现的警告
            var style = document.createElement('style');
            style.textContent = `
                [data-warning="autocomplete"],
                .chromium-warning,
                .password-warning,
                input[type="password"]::-webkit-contacts-auto-fill-button {
                    display: none !important;
                    visibility: hidden !important;
                    opacity: 0 !important;
                    pointer-events: none !important;
                }
            `;
            document.head.appendChild(style);
            
            // 为所有密码输入框添加autocomplete属性
            var passwordInputs = document.querySelectorAll('input[type="password"]');
            passwordInputs.forEach(function(input) {
                input.setAttribute('autocomplete', 'new-password');
            });
            """
            self.page.run_js(hide_warnings_js)
            
            # 检查页面状态
            js_check = """
            return {
                readyState: document.readyState,
                loading: window.performance.timing.loadEventEnd === 0
            }
            """
            page_state = self.page.run_js(js_check)
            
            # 如果页面仍在加载，再多等待一会儿
            if page_state and (page_state.get('readyState') != 'complete' or page_state.get('loading')):
                time.sleep(800)  # 等待800毫秒
            
            return True
                
        except Exception:
            return False
    
    def logout(self) -> bool:
        """
        退出登录
        
        Returns:
            bool: 退出是否成功
        """
        if not self.page:
            return True  # 已经关闭
        
        try:
            # 点击退出登录按钮
            logger.info("正在退出登录...")
            
            logger.info("退出登录成功")
            return True
            
        except Exception as e:
            logger.error(f"退出登录时发生异常: {e}")
            return False
        finally:
            # 无论退出是否成功，都关闭浏览器
            self.close()
    
    def close(self):
        """关闭浏览器"""
        if self.page:
            try:
                self.page.close()
                logger.info("已关闭浏览器")
            except Exception as e:
                logger.error(f"关闭浏览器时发生异常: {e}")
            finally:
                self.page = None 